import React, { useState, useEffect } from 'react';
import { Form, message, Modal, Table } from 'antd';

import { withRouter } from 'umi';
import { dictionaryList } from '@/services/dictionary';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import moment from 'moment';
import request from '@/utils/request';
import styles from './index.less';

const columnsModal = [
    {
        title: '工号',
        dataIndex: 'userNo',
        key: 'userNo'
    },
    {
        title: '打卡时间',
        dataIndex: 'attDatetime',
        key: 'attDatetime'
    },
    {
        title: '考勤来源',
        dataIndex: 'deviceName',
        key: 'deviceName'
    }
];

const LackCard = ({ form, dataSource = {}, location, formValueMap }) => {
    const user = JSON.parse(localStorage.getItem('user') || '{}');
    const { type, lackTime } = location.query;
    const { children: list = [] } = dataSource;

    // 这个是组织机构还没上的时候现在走新流程数据结构问题
    const employeeCode =
        dataSource?.employeeCode || formValueMap?.employeeCode || formValueMap?.userCode || user.employeeCode;

    const [lackCardTypeOptions, setLackCardTypeOptions] = useState([]);
    const [visible, setVisible] = useState(false);
    const [signDate, setSignDate] = useState('');
    const [attenddetail, setAttenddetail] = useState([]);

    // 显隐打卡记录modal
    const handleOnVisibleModal = () => {
        setVisible(!visible);
    };

    // 打卡记录
    const seeLackCardDetail = async () => {
        const lackDate = form.getFieldValue('lackDate');

        if (lackDate) {
            const param = {
                employeeCode,
                startTime: moment(lackDate).format('YYYY-MM-DD'),
                endTime: moment(lackDate).format('YYYY-MM-DD'),
                pageNo: 1,
                pageSize: 10
            };

            const { code, data } = await request('/api/work/v1/attendance/signdetail', {
                data: param,
                method: 'POST'
            });
            if (code === 10000) {
                setAttenddetail(data?.rows);
            }

            setSignDate(moment(lackDate).format('YYYY-MM-DD'));
            handleOnVisibleModal();
        } else {
            message.warning('请选择补卡时间');
        }
    };

    // 获取补卡类型
    const fetchResignInTypeOptions = async () => {
        const { data, code, msg } = await dictionaryList({ code: 'lackType' });
        if (code === 10000) {
            const arr = [];
            if (data.length > 0) {
                data.forEach(item => {
                    arr.push({ value: item.dictValue, label: item.dictName });
                });
            }
            setLackCardTypeOptions(arr.reverse());
        } else {
            message.error(msg);
        }
    };

    // 类型切换
    const handleTypeChange = () => {
        form.setFieldsValue({ lackDate: undefined });
    };

    useEffect(() => {
        fetchResignInTypeOptions();
    }, []);

    const { getFieldDecorator } = form;
    return (
        <>
            {list.length > 0 &&
                list.map(item => {
                    const { formId, label, extra, rules } = item;
                    let { initialValue } = item;
                    const obj = {};
                    let extraCopy = extra;
                    let className;
                    if (formId === 'lackType') {
                        obj.onChange = handleTypeChange;
                        item = { ...item, dataList: lackCardTypeOptions };
                        initialValue = initialValue || type;
                    }

                    if (formId === 'lackDate') {
                        className = styles.bksj;
                        extraCopy = (
                            <a
                                href="#"
                                onClick={e => {
                                    e.preventDefault();
                                    seeLackCardDetail();
                                }}
                            >
                                查看打卡记录
                            </a>
                        );
                        initialValue = initialValue || (lackTime && decodeURI(lackTime));
                    }

                    return (
                        <Form.Item label={label} key={formId} className={className} extra={extraCopy}>
                            {getFieldDecorator(formId, {
                                initialValue,
                                rules
                            })(<AutoRenderComponent form={form} config={item} {...obj} />)}
                        </Form.Item>
                    );
                })}

            <Modal
                title={
                    <div>
                        <div style={{ fontSize: '20px', color: '#333' }}>查看打卡记录</div>
                        <p
                            style={{
                                color: 'rgba(0, 0, 0, .45)',
                                fontSize: '14px',
                                marginBottom: 0
                            }}
                        >
                            {signDate}
                            打卡数据
                        </p>
                    </div>
                }
                width={600}
                footer={null}
                visible={visible}
                onOk={handleOnVisibleModal}
                onCancel={handleOnVisibleModal}
                centered
            >
                <Table dataSource={attenddetail} columns={columnsModal} pagination={false} rowKey="id" />
            </Modal>
        </>
    );
};

export default withRouter(LackCard);
